package cn.tedu.storage.tcc;

import cn.tedu.storage.entity.Storage;
import cn.tedu.storage.mapper.StorageMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class StorageTccActionImpl implements StorageTccAction {
    @Autowired
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public boolean prepareDecreaseStorage(BusinessActionContext ctx, Long productId, Integer count) {
        //判断有没有足够库存
        Storage storage = storageMapper.selectById(productId);
        if (storage.getResidue() < count) {
            throw new RuntimeException(
                "库存不足，不能完成冻结操作："+storage.getResidue()+" < "+count);
        }
        //冻结库存
        storageMapper.updateFrozen(
                productId,
                storage.getResidue()-count,
                storage.getFrozen()+count);
        //一阶段成功，保存一个标记，用来控制幂等性
        ResultHolder.setResult(StorageTccAction.class,ctx.getXid(),"p");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //幂等性控制，如果没有标记，表示已经提交过，不再进行提交
        if (ResultHolder.getResult(StorageTccAction.class, ctx.getXid()) == null) {
            return true;
        }
        //获得业务数据，完成提交操作
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToUsed(productId,count);
        //提交完成后删除标记
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        //幂等性控制，如果没有标记，表示已经提交过，不再进行提交
        if (ResultHolder.getResult(StorageTccAction.class, ctx.getXid()) == null) {
            return true;
        }
        //获得业务数据，完成提交操作
        Long productId = Long.valueOf(ctx.getActionContext("productId").toString());
        Integer count = Integer.valueOf(ctx.getActionContext("count").toString());
        storageMapper.updateFrozenToResidue(productId,count);
        //提交完成后删除标记
        ResultHolder.removeResult(StorageTccAction.class, ctx.getXid());
        return true;
    }
}
